package com.epfly.promo.activity.impl.discount.predicate;

import com.epfly.iface.promo.activity.enums.IsActiveEnum;
import com.epfly.promo.activity.dao.ActivityDinnerBoundMapper;
import com.epfly.promo.activity.dao.UserActivityDinnerStatisticsMapper;
import com.epfly.promo.activity.entity.ActivityDinnerBoundEntity;
import com.epfly.promo.activity.entity.ActivityEntity;
import com.epfly.promo.activity.entity.UserActivityDinnerStatisticsEntity;
import com.epfly.promo.activity.feign.DataRestaurantFeignService;
import com.epfly.promo.activity.impl.discount.ActivityWrapper;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 餐别级限额限次过滤
 */
@Order(value = PredicateOrder.BOUND_DINNER_ORDER)
@Service
public class BoundDinnerPredicate implements ActivityDiscountPredicate {

    @Resource
    private ActivityDinnerBoundMapper activityDinnerBoundMapper;

    @Resource
    private UserActivityDinnerStatisticsMapper userActivityRuleMapper;

    @Resource
    private DataRestaurantFeignService dataRestaurantFeignService;

    @Resource
    private BoundPredicateHelper boundPredicateHelper;


    @Override
    public boolean test(ActivityWrapper activityWrapper) {

        if (boundPredicateHelper.assertBasic(activityWrapper)) {
            return true;
        }

        ActivityEntity activityEntity = activityWrapper.getActivityEntity();

        // 用户ID
        String userID = activityWrapper.getUserID();

        // 根据订单时间计算餐别
        Byte dinnerType = dataRestaurantFeignService.getMealType(activityWrapper.getMerchantId(), activityWrapper.getStoreId(), activityWrapper.getOrderTime()).byteValue();

        ActivityDinnerBoundEntity dinnerBoundEntity = activityDinnerBoundMapper.findByActivityIdAndDinnerTypeAndIsActive(activityEntity.getId(), dinnerType, IsActiveEnum.YES.getKey());

        if (boundPredicateHelper.assertBoundBasic(dinnerBoundEntity)) {
            return true;
        }

        UserActivityDinnerStatisticsEntity userActivityRuleEntity = userActivityRuleMapper.findByUserIdActivityIdAndDinnerType(userID, activityEntity.getId(), dinnerType);

        return boundPredicateHelper.assertBoundRule(userActivityRuleEntity, dinnerBoundEntity);
    }
}
